package com.ruoyi.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.domain.SysTenantModule;
import com.ruoyi.system.domain.bo.SysTenantBo;
import com.ruoyi.system.domain.vo.SysBusinessModuleVo;
import com.ruoyi.system.domain.vo.SysTenantVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysTenantService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-20
 */
@RequiredArgsConstructor
@Service
public class SysTenantServiceImpl implements ISysTenantService {

    private final SysTenantMapper baseMapper;

    private final SysDeptMapper deptMapper;

    private final SysUserMapper userMapper;

    private final SysBusinessModuleMapper sysBusinessModuleMapper;

    private final SysTenantModuleMapper sysTenantModuleMapper;

    /**
     * 查询租户管理
     *
     * @param id 租户管理主键
     * @return 租户管理
     */
    @Override
    public SysTenantVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据租户id 查询购买模块
     *
     * @param tenantId
     * @return
     */
    @Override
    public List<SysBusinessModuleVo> queryBusinessModuleByTenantId(String tenantId) {
        // TODO 根据id查询租户购买模块
        return sysBusinessModuleMapper.selectBusinessModuleByTenantId(tenantId);
    }

    /**
     * 新增租户购买管理
     *
     * @param tms 租户管理
     * @return 结果
     */
    @Override
    public Boolean insertOrUpdateBuyModule(List<SysTenantModule> tms) {
        int index = 0;
        for (SysTenantModule vo : tms) {
            if (vo.getId() != null) {
                index = sysTenantModuleMapper.updateById(vo);
            } else {
                index = sysTenantModuleMapper.insert(vo);
            }
        }
        return index > 0;
    }

    /**
     * 查询租户管理列表
     *
     * @param bo 租户管理
     * @return 租户管理
     */
    @Override
    public TableDataInfo<SysTenantVo> queryPageList(SysTenantBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        Page<SysTenantVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询租户管理列表
     *
     * @param bo 租户管理
     * @return 租户管理
     */
    @Override
    public List<SysTenantVo> queryList(SysTenantBo bo) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysTenant> buildQueryWrapper(SysTenantBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenant> lqw = Wrappers.lambdaQuery();
        lqw.ne(true, SysTenant::getTenantId, "000000");
        lqw.like(StringUtils.isNotBlank(bo.getContact()), SysTenant::getContact, bo.getContact());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), SysTenant::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysTenant::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getTenantId()), SysTenant::getTenantId, bo.getTenantId());
        return lqw;
    }

    /**
     * 新增租户管理
     *
     * @param bo 租户管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysTenantBo bo) {
        SysTenant add = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        return flag;
    }


    /**
     * 修改租户管理
     *
     * @param bo 租户管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysTenantBo bo) {
        SysTenant update = BeanUtil.toBean(bo, SysTenant.class);
        if (update.getId() == null) {
            throw new ServiceException("更新时缺少主键！");
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysTenant entity) {
        if (entity.getId() != null) {
            SysTenantVo sysTenantVo = baseMapper.selectVoById(entity.getId());
            // 判断修改的手机号是否在租户下重复
            Map<String, Object> map = new HashMap(2);
            map.put("userName", entity.getPhone());
            map.put("tenantId", entity.getTenantId());
            SysUser sysUserByUserName = userMapper.selectUserByUserNameAndTenantId(map);
            if (sysUserByUserName != null) {
                if (sysUserByUserName.getUserId().longValue() != sysTenantVo.getUserId().longValue()) {
                    // 更换租户管理员
                    SysUser sysUser = new SysUser();
                    sysUser.setUserId(sysTenantVo.getUserId());
                    sysUser.setTenantAdmin("0");
                    userMapper.updateTenantAdminByUserId(sysUser);
                    sysUser = new SysUser();
                    sysUser.setUserId(sysUserByUserName.getUserId());
                    sysUser.setPhonenumber(entity.getPhone());
                    sysUser.setUserName(entity.getPhone());
                    sysUser.setNickName(entity.getName());
                    sysUser.setTenantAdmin("1");
                    userMapper.updateTenantAdminByUserId(sysUser);
                    entity.setUserId(sysUserByUserName.getUserId());
                    return;
                }
            }
            SysUser sysUser = new SysUser();
            sysUser.setUserId(sysTenantVo.getUserId());
            sysUser.setPhonenumber(entity.getPhone());
            sysUser.setUserName(entity.getPhone());
            sysUser.setNickName(entity.getName());
            userMapper.updateTenantAdminByUserId(sysUser);
        } else {
            // 根据自增规则处理租户ID
            String maxTenantId = baseMapper.getMaxTenantId();
            String lastNum = String.valueOf(Integer.parseInt(maxTenantId) + 1);
            int zLength = 6 - String.valueOf(Integer.parseInt(maxTenantId) + 1).length();
            maxTenantId = "";
            for (int index = 0; index < zLength; index++) {
                maxTenantId += "0";
            }
            maxTenantId += lastNum;
            entity.setTenantId(maxTenantId);
            entity.setDelFlag("0");
            //根据添加时填写的租户信息添加租户部门和租户管理员
            SysDept sysDept = new SysDept();
            sysDept.setDeptName(entity.getName());
            sysDept.setStatus("0");
            sysDept.setPhone(entity.getPhone());
            sysDept.setLeader(entity.getContact());
            sysDept.setTenantId(entity.getTenantId());
            deptMapper.insert(sysDept);
            SysUser sysUser = new SysUser();
            sysUser.setPassword(BCrypt.hashpw(SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.tenant.password")));
            sysUser.setPhonenumber(entity.getPhone());
            sysUser.setUserName(entity.getPhone());
            sysUser.setNickName(entity.getName());
            sysUser.setStatus("0");
            sysUser.setDelFlag("0");
            sysUser.setTenantId(maxTenantId);
            sysUser.setTenantAdmin("1");
            sysUser.setSystemAdmin("0");
            sysUser.setDeptId(sysDept.getDeptId());
            userMapper.insert(sysUser);
            entity.setUserId(sysUser.getUserId());
        }
    }

    /**
     * 批量删除租户管理
     *
     * @param ids 需要删除的租户管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 删除租户需要删除租户下全部用户
            userMapper.updateBatchByTenantIds((List<Long>) ids);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
